package org.zhengquan.service;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zhengquan.common.RequestHolder;
import org.zhengquan.dao.SysRoleUserMapper;
import org.zhengquan.dao.SysUserMapper;
import org.zhengquan.dto.PageResult;
import org.zhengquan.exception.ParamException;
import org.zhengquan.pojo.SysRole;
import org.zhengquan.pojo.SysUser;
import org.zhengquan.util.BeanValidator;
import org.zhengquan.util.IpUtil;
import org.zhengquan.util.MD5Util;
import org.zhengquan.util.PasswordUtil;
import org.zhengquan.vo.PageQuery;
import org.zhengquan.vo.UserVO;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhengquan
 * @date 2017/10/31
 */
@Service
public class SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private SysLogService sysLogService;

    public void save(UserVO userVO) {
        BeanValidator.check(userVO);
        if (checkTelephoneExit(userVO.getTelephone(), userVO.getId())) {
            throw new ParamException("手机号码已被占用");
        }
        if (checkEmailExit(userVO.getMail(), userVO.getId())) {
            throw new ParamException("Email已被占用");
        }
        String password = PasswordUtil.randomPassword();
        password = MD5Util.MD5EncodeUtf8("123456");


        SysUser sysUser = SysUser.builder().username(userVO.getUsername()).telephone(userVO.getTelephone())
                .mail(userVO.getMail()).password(password).deptId(userVO.getDeptId())
                .state(userVO.getState()).remark(userVO.getRemark()).build();
        sysUser.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysUser.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysUser.setOperateTime(new Date());

//        String message = "恭喜您成为本系统的新管理员,请尽快登录确认,账号为手机或email地址,密码为:123456";
//        Set<String>receivers = Sets.newHashSet();
//        receivers.add(sysUser.getMail());
//        MailUtil.send(Mail.builder().subject("新管理员通知").message(message).receivers(receivers).build());

        sysUserMapper.insertSelective(sysUser);
        sysLogService.saveUserLog(null,sysUser);
    }

    public void update(UserVO userVO) {
        BeanValidator.check(userVO);
        if (checkTelephoneExit(userVO.getTelephone(), userVO.getId())) {
            throw new ParamException("手机号码已被占用");
        }
        if (checkEmailExit(userVO.getMail(), userVO.getId())) {
            throw new ParamException("Email已被占用");
        }
        SysUser before = sysUserMapper.selectByPrimaryKey(userVO.getId());
        Preconditions.checkNotNull(before, "待更新的用户不存在");
        SysUser after = SysUser.builder().id(userVO.getId()).username(userVO.getUsername()).telephone(userVO.getTelephone())
                .mail(userVO.getMail()).password(before.getPassword()).deptId(userVO.getDeptId())
                .state(userVO.getState()).remark(userVO.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveUserLog(before,after);
    }

    public SysUser selectUserByKeyword(String keyword) {
        return sysUserMapper.selectByKeyword(keyword);
    }

    public PageResult<SysUser> selectPageByDeptId(Integer deptId, PageQuery pageQuery) {
        BeanValidator.check(pageQuery);
        int count = sysUserMapper.countByDeptId(deptId);
        if (count > 0) {
            List<SysUser> list = sysUserMapper.selectPageByDeptId(deptId, pageQuery);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    public List<SysUser> selectAllUsers() {
        return sysUserMapper.selectAllUsers();
    }

    public List<SysUser> selectLisyByRoleList(List<SysRole> roleList) {
        if (CollectionUtils.isEmpty(roleList)) {
            return Lists.newArrayList();
        }
        List<Integer> roleIdList = roleList.stream().map(sysRole -> sysRole.getId()).collect(Collectors.toList());
        List<Integer> userIdList = sysRoleUserMapper.selectUserIdListByRoleIdList(roleIdList);
        if(CollectionUtils.isEmpty(userIdList)){
            return Lists.newArrayList();
        }
        return sysUserMapper.selectByIdList(userIdList);
    }

    private boolean checkEmailExit(String email, Integer userId) {
        return sysUserMapper.countByMail(email, userId) > 0;
    }

    private boolean checkTelephoneExit(String telephone, Integer userId) {
        return sysUserMapper.countByTelephone(telephone, userId) > 0;
    }
}
